#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include <string>
#include <sys/types.h>
#include <unistd.h>

using namespace std;

void Usage(string proc)
{
    cout << "\n\rUsage:" << proc << "serverip serverport\n" << endl;
}

//客户端: 输入服务端的端口号以及IP地址
// ./udpclient serverip serverport
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }

    string serverip = argv[1];
    //字符串转整形
    uint16_t serverport = stoi(argv[2]);

    //服务端: 绑定客户端的IP地址和端口号;
    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    socklen_t len = sizeof(server);

    //客户端的绑定是os进行随机绑定的.不需要自己绑定, 只要保证服务端的ip和端口号唯一即可.
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        cout << "socket error" << endl;
        return -1;
    }

    string message;
    char buffer[1024];
    while(true)
    {
        cout << "please Enter@ ";
        getline(cin, message);

        //服务端的数据message发送给客户端
        sendto(sockfd, message.c_str(), message.size(), 0, (const struct sockaddr *)&server, sizeof(len));

        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);

        //接收服务端的数据
        ssize_t s = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&temp, &len);
        if(s > 0)
        {
            buffer[s] = 0;
            cout << buffer << endl;
        }
    }
    close(sockfd);
    return 0;
}